const announce = require('../db/models/announce.js');
const mongoose = require('mongoose');

// 获取公告列表
exports.list = async ( req, res )=> {
  const listQuery = req.query;
  let pageSize = 9999;
  let pageNum = 1;
  if(listQuery.pageSize) pageSize = listQuery.pageSize;
  if(listQuery.pageNum) pageNum = listQuery.pageNum;
  const skip = (pageNum - 1) * pageSize;
  const total = await announce.countDocuments();
  try{
    const findRes =  await announce.find({}, { __v: 0 }).skip(skip).limit(pageSize);
    res.status(200).send({ code: 200, message: "查询成功", data: findRes, total });
  }catch(e){
    console.log("err>>>", err);
    res.status(404).send({ code: 404, message: "查询失败" });
  }
}

// 搜索公告
exports.search = async ( req, res )=> {
  const regParams = regFn(req.body, ['title', 'name']);
  if(Object.keys(regParams).length === 0) {
    res.status(200).send({ code: 200, message: "搜索成功", data: [] });
    return;
  }
  try{
    const findRes = await announce.find( { $or: regParams });
    res.status(200).send({ code: 200, message: "搜索成功", data: findRes, total: findRes.length });
  }catch(err){
    console.log("err>>>", err);
    res.status(404).send({ code: 404, message: "搜索失败" });
  }
}

// 新增公告
exports.add = async ( req, res )=> {
  const addInfo = req.body;
  if(!addInfo.title || !addInfo.name || !addInfo.content) {
    res.status(404).send({ code: 404, message: "缺少必要参数" });
    return;
  }
  try{
    const maxRes =  await announce.aggregate([{$group: { _id: null, maxValue: { $max: '$id' } }}])
    if(maxRes.length === 0) await announce.create({ ...addInfo, id: 0 });
    else await announce.create({ ...addInfo, id: maxRes[0].maxValue + 1 });
    res.status(200).send({ code: 200, message: "新增成功" });
  }catch(err){
    console.log("err>>>", err);
    res.status(404).send({ code: 404, message: "新增失败" });
  }
};
// 更新公告
exports.update = async ( req, res )=> {
  const updateInfo = req.body;
  const isObjectId = mongoose.Types.ObjectId.isValid(updateInfo._id);
  if(!updateInfo._id || !isObjectId || !updateInfo.title || !updateInfo.name || !updateInfo.content) {
    res.status(404).send({ code: 404, message: "缺少必要参数" });
    return;
  }
  try{
    const findRes = await announce.find({ _id: updateInfo._id });
    if(findRes.length === 0){
      res.status(404).send({ code: 404, message: "修改失败" });
      return;
    }
    let updateOptions = { $set: { title: updateInfo.title, name: updateInfo.name, content: updateInfo.content } };
    await announce.updateOne({ _id: updateInfo._id }, updateOptions);
    res.status(200).send({ code: 200, message: "修改成功" });
  }catch(err){
    console.log("err>>>", err);
    res.status(404).send({ code: 404, message: "新增失败" });
  }
};
// 删除公告
exports.delete = async ( req, res )=> {
  const deleteInfo = req.query;
  const isObjectId = mongoose.Types.ObjectId.isValid(deleteInfo.id);
  if(!deleteInfo || !isObjectId || !deleteInfo.id){
    res.status(404).send({ code: 404, message: "缺少必要参数" });
    return;
  }
  const deleteRes = await announce.deleteOne({ _id: deleteInfo.id });
  if(deleteRes.deletedCount === 0) {
    res.status(404).send({ code: 404, message: "删除失败" });
    return;
  }
  res.status(200).send({ code: 200, message: "删除成功" });
};

// 多条件模糊搜索
const regFn = (reqBody, arr) => {
  if (!reqBody) return [];
  return arr.map(key => {
    const value = reqBody[key];
    if (!value || value === "") return null;
    return { [key]: new RegExp(value, 'i') };
  }).filter(Boolean);
}